import axios from '../js_sdk/xtshadow-axios/axios.min'
import store from '../store'
import {
	paramsToStr,
	toast
} from './tools'


import {baseURL} from '../config/app'


function checkParams(params) {
	if (typeof params != 'object') return params
	for (let key in params) {
		const value = params[key];
		if (value === null || value === undefined || value === "") {
			delete params[key];
		}
	}
	return params;
}



const service = axios.create({
	baseURL: baseURL,
	timeout: 10000,
	header: {
		'content-type': 'application/json;charset:utf-8'
	},

});


// request拦截器
service.interceptors.request.use(
	config => {
		config.data = checkParams(config.data)
		config.params = checkParams(config.params)
		if (config.method == 'GET') {
			config.url += paramsToStr(config.params)
		}
		config.header.token = store.getters.token
		uni.showLoading({
		    title: "加载数据中"
		})
		return config
	},
	error => {
		 uni.hideLoading()
		// Do something with request error
		console.log(error) // for debug
		Promise.reject(error)
	}
)

// response 拦截器
service.interceptors.response.use(
	async (response) => {
			uni.hideLoading()
			return Promise.resolve(response.data)
		},
		error => {
			uni.showToast({
				title: "系统错误",
				icon: "none"
			})
			uni.hideLoading()
			console.log(error)
			console.log('err' + error) // for debug
			return Promise.reject(error)
		}
)

export default service
